﻿using Dapper;
using Inventorycount.API.Read.Application.Command;
using Inventorycount.Dto;
using Inventorycount.ErrorCode;
using MediatR;
using System.Data;

namespace Inventorycount.API.Read.Application.CommandHandLer
{
    public class GetinboundCommandHandLer : IRequestHandler<GetinboundCommand, APIResult<List<InboundDto>>>
    {
        private readonly IDbConnection repository;

        public GetinboundCommandHandLer(IDbConnection repository)
        {
            this.repository = repository;
        }

        public async Task<APIResult<List<InboundDto>>> Handle(GetinboundCommand request, CancellationToken cancellationToken)
        {
            var result = new APIResult<List<InboundDto>>
            {
                Code = ResultCode.Ok,
                Message = "查询成功"
            };

            try
            {
                // 构建SQL查询语句
                var sql = @"
                    SELECT 
                        o.Id,
                        o.Inbound_code,
                        o.Transfer_id,
                        o.Warehouse_id,
                        o.Status,
                        o.Operator_id,
                        o.Operate_time,
                        o.Remark,
                        d.Id AS Id,  -- 分割点
                         d.Transfer_id,
                        d.Inbound_id,
                        d.Operator_id,
                        d.Goods_id,
                        d.Quantity,
                        d.Price,
                        d.Status AS DetailStatus,
                        d.Create_time,
                        d.Remark AS DetailRemark
                    FROM Wms_inbound_order o
                    JOIN Wms_Inbound_record d ON o.Id = d.Inbound_id
                    WHERE o.IsDeleted =0";
                if (request.Transfer_id.HasValue)
                {
                    sql += " AND o.Transfer_id = @Transfer_id";
                }

                // 使用Dapper的多映射功能
                var outboundDictionary = new Dictionary<int, InboundDto>();

                var parameters = new DynamicParameters();
                if (request.Transfer_id.HasValue)
                {
                    parameters.Add("Transfer_id", request.Transfer_id.Value);
                }

                await repository.QueryAsync<InboundDto, InboundrecordDto, InboundDto>(
                    sql,
                    (outbound, detail) =>
                    {
                        if (!outboundDictionary.TryGetValue(outbound.Id, out var outboundEntry))
                        {
                            outboundEntry = outbound;
                            outboundEntry.Inboundrecord = new List<InboundrecordDto>();
                            outboundDictionary.Add(outbound.Id, outboundEntry);
                        }

                        if (detail != null)
                        {
                            outboundEntry.Inboundrecord.Add(detail);
                        }
                        return outboundEntry;
                    },
                    param: parameters,
                    splitOn: "Id");

                result.Data = outboundDictionary.Values.ToList();
            }
            catch (Exception ex)
            {
                result.Code = ResultCode.Fail;
                result.Message = $"查询失败: {ex.Message}";
            }

            return result;
        }

    }
}
